<template>
    <div class="orders-page">
        <h2>订单管理</h2>

        <!-- 搜索栏 -->
        <el-card class="search-card">
            <el-form :inline="true" :model="searchForm">
                <el-form-item label="订单号">
                    <el-input v-model="searchForm.orderId" placeholder="请输入订单号" />
                </el-form-item>
                <el-form-item label="商品名称">
                    <el-input v-model="searchForm.productName" placeholder="请输入商品名称" />
                </el-form-item>
                <el-form-item label="订单状态">
                    <el-select v-model="searchForm.status" placeholder="请选择状态">
                        <el-option label="全部" value="" />
                        <el-option label="待付款" value="pending" />
                        <el-option label="待发货" value="processing" />
                        <el-option label="已发货" value="shipped" />
                        <el-option label="已完成" value="completed" />
                        <el-option label="已取消" value="cancelled" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 订单列表 -->
        <el-table :data="orders" stripe style="margin-top: 20px;">
            <el-table-column type="expand">
                <template #default="{ row }">
                    <div class="order-detail">
                        <el-descriptions :column="2" border>
                            <el-descriptions-item label="买家留言">{{ row.buyerMessage || '无' }}</el-descriptions-item>
                            <el-descriptions-item label="收货地址">{{ row.address }}</el-descriptions-item>
                            <el-descriptions-item label="创建时间">{{ row.createdAt }}</el-descriptions-item>
                            <el-descriptions-item label="支付时间">{{ row.paidAt || '未支付' }}</el-descriptions-item>
                            <el-descriptions-item label="发货时间">{{ row.shippedAt || '未发货' }}</el-descriptions-item>
                            <el-descriptions-item label="完成时间">{{ row.completedAt || '未完成' }}</el-descriptions-item>
                        </el-descriptions>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="id" label="订单号" width="180" />
            <el-table-column prop="product.name" label="商品名称" min-width="200" />
            <el-table-column prop="buyer.username" label="买家" width="120" />
            <el-table-column prop="amount" label="金额" width="120">
                <template #default="{ row }">
                    ¥{{ row.amount }}
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                    <el-tag :type="getStatusType(row.status)">
                        {{ getStatusText(row.status) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                    <el-button-group>
                        <el-button v-if="row.status === 'processing'" size="small" type="primary"
                            @click="shipOrder(row)">
                            发货
                        </el-button>
                        <el-button v-if="row.status === 'pending'" size="small" type="danger" @click="cancelOrder(row)">
                            取消
                        </el-button>
                        <el-button size="small" type="info" @click="viewOrderDetail(row)">
                            详情
                        </el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
                :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>

        <!-- 发货对话框 -->
        <el-dialog v-model="shipDialogVisible" title="订单发货" width="500px">
            <el-form ref="shipForm" :model="shipForm" :rules="shipRules" label-width="100px">
                <el-form-item label="快递公司" prop="courier">
                    <el-select v-model="shipForm.courier" placeholder="请选择快递公司">
                        <el-option label="顺丰速运" value="SF" />
                        <el-option label="中通快递" value="ZTO" />
                        <el-option label="圆通速递" value="YTO" />
                        <el-option label="韵达快递" value="YD" />
                        <el-option label="申通快递" value="STO" />
                    </el-select>
                </el-form-item>
                <el-form-item label="快递单号" prop="trackingNumber">
                    <el-input v-model="shipForm.trackingNumber" placeholder="请输入快递单号" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="shipDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitShipForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
    orderId: '',
    productName: '',
    status: ''
})

// 订单列表数据
const orders = ref([
    {
        id: 'SO2024040701',
        product: { name: '二手笔记本电脑' },
        buyer: { username: '张三' },
        amount: 2999,
        status: 'processing',
        buyerMessage: '请尽快发货',
        address: '北京市海淀区中关村大街1号',
        createdAt: '2024-04-07 10:00:00',
        paidAt: '2024-04-07 10:05:00',
        shippedAt: null,
        completedAt: null
    }
])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 发货对话框相关
const shipDialogVisible = ref(false)
const currentOrder = ref(null)
const shipForm = reactive({
    courier: '',
    trackingNumber: ''
})

const shipRules = {
    courier: [
        { required: true, message: '请选择快递公司', trigger: 'change' }
    ],
    trackingNumber: [
        { required: true, message: '请输入快递单号', trigger: 'blur' },
        { pattern: /^[A-Za-z0-9]+$/, message: '快递单号格式不正确', trigger: 'blur' }
    ]
}

// 获取状态类型
const getStatusType = (status: string) => {
    const types = {
        pending: 'warning',
        processing: 'primary',
        shipped: 'info',
        completed: 'success',
        cancelled: 'danger'
    }
    return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
    const texts = {
        pending: '待付款',
        processing: '待发货',
        shipped: '已发货',
        completed: '已完成',
        cancelled: '已取消'
    }
    return texts[status] || status
}

// 搜索方法
const handleSearch = () => {
    // TODO: 实现搜索逻辑
    console.log('搜索条件:', searchForm)
}

// 重置搜索
const resetSearch = () => {
    searchForm.orderId = ''
    searchForm.productName = ''
    searchForm.status = ''
    handleSearch()
}

// 分页方法
const handleSizeChange = (val: number) => {
    pageSize.value = val
    handleSearch()
}

const handleCurrentChange = (val: number) => {
    currentPage.value = val
    handleSearch()
}

// 发货
const shipOrder = (order: any) => {
    currentOrder.value = order
    shipForm.courier = ''
    shipForm.trackingNumber = ''
    shipDialogVisible.value = true
}

// 提交发货表单
const submitShipForm = async () => {
    if (!currentOrder.value) return

    try {
        // TODO: 调用API更新订单状态和物流信息
        const order = currentOrder.value
        order.status = 'shipped'
        order.shippedAt = new Date().toISOString()
        shipDialogVisible.value = false
        ElMessage.success('发货成功')
    } catch (error) {
        ElMessage.error('发货失败')
    }
}

// 取消订单
const cancelOrder = async (order: any) => {
    try {
        await ElMessageBox.confirm('确定要取消该订单吗？', '警告', {
            type: 'warning'
        })
        // TODO: 调用API取消订单
        order.status = 'cancelled'
        ElMessage.success('订单已取消')
    } catch {
        // 用户取消操作
    }
}

// 查看订单详情
const viewOrderDetail = (order: any) => {
    // TODO: 实现查看订单详情的逻辑
    console.log('查看订单详情:', order)
}
</script>

<style scoped>
.orders-page {
    padding: 20px;
}

h2 {
    margin-bottom: 20px;
    font-size: 24px;
    color: #333;
}

.search-card {
    margin-bottom: 20px;
}

.order-detail {
    padding: 20px;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>